<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <backView />
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">编辑接种记录</text>
    <FormView v-if="form.name" :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { healthVaccFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'
import backView from '@/components/backView.vue'

const form = reactive<any>({})
const recordId = ref('')

onMounted(async () => {
  console.log('编辑接种记录页面加载')
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    recordId.value = params.id
    await loadRecord(params.id)
  }
})

async function loadRecord(id: string) {
  try {
    const result = await request.get<any>(`/health_records/health_vacc/healthVaccInfo/queryById?id=${id}`, {}, {
      useErrMsg: true
    })
    
    if (result.success) {
      Object.assign(form, result.success)
    }
  } catch (error) {
    console.error('加载记录失败:', error)
    Taro.showToast({ title: '加载记录失败', icon: 'error' })
  }
}

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    if (!form.name) {
      Taro.showToast({ title: '请输入姓名', icon: 'error' })
      return
    }
    if (!form.idNumber) {
      Taro.showToast({ title: '请输入证件号码', icon: 'error' })
      return
    }
    if (!form.vaccName) {
      Taro.showToast({ title: '请输入接种疫苗名称', icon: 'error' })
      return
    }
    if (!form.vaccDate) {
      Taro.showToast({ title: '请选择接种时间', icon: 'error' })
      return
    }
    if (!form.vaccUnit) {
      Taro.showToast({ title: '请输入接种单位', icon: 'error' })
      return
    }

    // 提交数据
    const params = {
      ...form,
      id: recordId.value,
      // 确保日期格式正确
      vaccDate: form.vaccDate ? new Date(form.vaccDate).toISOString() : null
    }
    
    const result = await request.put<any>('/health_records/health_vacc/healthVaccInfo/edit', params, {
      useErrMsg: true
    })
    
    if (result) {
      Taro.showToast({ title: '更新成功', icon: 'success' })
      // 返回上一页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('更新失败:', error)
    Taro.showToast({ title: '更新失败', icon: 'error' })
  }
}
</script>
